package com.vimi8.chick.plugins.module;

import android.content.Context;
import android.content.pm.PackageInfo;

import com.alibaba.fastjson.JSON;
import com.alibaba.weex.plugin.annotation.WeexModule;
import com.eros.framework.utils.JsPoster;
import com.taobao.weex.annotation.JSMethod;
import com.taobao.weex.bridge.JSCallback;
import com.taobao.weex.common.WXModule;
import com.vimi8.chick.plugins.model.DownloadServiceListener;
import com.vimi8.chick.plugins.model.UpdateInfo;
import com.vimi8.chick.plugins.utils.ServiceUtil;

import java.util.HashMap;

@WeexModule(name = "vmVersion", lazyLoad = true)
public class VersionModule extends WXModule {

    @JSMethod
    public void getVersionInfo(String params, JSCallback jsCallback) {
        Context context = mWXSDKInstance.getContext();
        try {
            PackageInfo pm = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            HashMap data = new HashMap();
            data.put("firstInstallTime", pm.firstInstallTime);
            data.put("versionName", pm.versionName);
            data.put("versionCode", pm.versionCode);
            data.put("packageName", pm.packageName);
            data.put("channel", ServiceUtil.INSTANCE.getBuildConfigValue(pm.packageName, "FLAVOR"));
            JsPoster.postSuccess(data, jsCallback);
        } catch (Exception e) {
            e.printStackTrace();
            JsPoster.postFailed("获取版本信息失败", jsCallback);
        }
    }

    @JSMethod
    public void downloadAndInstall(String params, final JSCallback jsCallback) {
        Context context = mWXSDKInstance.getContext();
        UpdateInfo bean = JSON.parseObject(params, UpdateInfo.class);
        String downloadUrl = bean.getDownloadUrl();
        if (downloadUrl == null) {
            JsPoster.postFailed("没有下载地址", jsCallback);
            return;
        }
        ServiceUtil.INSTANCE.startDownloadService(
            context,
            bean.getVersionTips(),
            downloadUrl,
            new DownloadServiceListener(jsCallback)
        );
    }
}
